
function ImageLib() {
    const CHECK_IMG_TYPES = ['png', 'jpeg'];
    let _file = null;

    let _canvas = document.createElement('canvas');
    let _context = _canvas.getContext('2d');
    let _reader = new FileReader();
    let _img = document.createElement('img');
    let _isReady = false;
    let _defType = ''; //缓存的最优的格式
    let _lastImageType = ''; //上次获取DataURL的格式
    let _targetSize = null;

    let _ensureReady = function(errMsg) {
        if (!_isReady) {
            throw errMsg || "cannot call the interface when image is not ready"
        }
    }
    this.hasAlphaPixel = function() {
        _ensureReady(arguments.callee.name)
        imageData = _context.getImageData(0, 0, _canvas.width, _canvas.height).data;
        for (var index = 3; index < imageData.length; index += 4) {
            if (imageData[index] != 255) {
                return true;  
            }
        }
        return false;
    }

    this.setFile = function(file, readyCbk) {
        if (!(file instanceof File) || file.type.indexOf('image/') != 0) {
            throw "invaid file type";
        }

        console.log('lodding', file.name);
        _file = file;
        _isReady = false;
        _defType = '';
        _lastImageType = '';
        _reader.onload = function (e) {
            _img.src = e.target.result;
            console.log(_img.src.length, file.size, _img.src.length / file.size)
            _img.onload = function() {
                _isReady = true;
                readyCbk && readyCbk(true);  
            }
        }
        _reader.readAsDataURL(file);
        // _reader.onerror = function() {
        //     console.error('failed to read file:' + file.name);
        //     readyCbk && readyCbk(false); 
        // }
    }

    //获取高质量的目标格式，支持检查的类型：CHECK_IMG_TYPES
    this.getBestType = function() {
        if (_defType) return _defType;
        _ensureReady();

        //调整为不超过100*100的图片进行透明像素的判断，避免大文件的低效率
        let size = _calcSizeByMax(200, 200);
        let sampleWidth = size.width;
        let sampleHeight = size.height;
        _canvas.width = sampleWidth;
        _canvas.height = sampleHeight;
        _context.clearRect(0, 0, sampleWidth, sampleHeight);
        _context.drawImage(_img, 0, 0, sampleWidth, sampleHeight);

        if (this.hasAlphaPixel()) {
            _defType = 'png';
        } else {
            let sizeMap = {};
            CHECK_IMG_TYPES.forEach(type => {
                let newUrl = _canvas.toDataURL(`image/${type}`, 1);
                sizeMap[type] = newUrl.length;
            });
            _defType = sizeMap['png'] < sizeMap['jpeg'] ? 'png' : 'jpeg';  
        }
        return _defType;
    }

    let _calcSizeByMax = function(maxWidth, maxHeight) {
        if (maxWidth <= 0 || maxHeight <= 0) {
            throw 'invalid size value for the image';
        }
        _ensureReady();
        let sampleWidth = _img.width;
        let sampleHeight = _img.height;
        let imgRatio = _img.width / _img.height;
        if (imgRatio > maxWidth / maxHeight) {
            if (_img.width > maxWidth) {
                sampleWidth = maxWidth;
                sampleHeight = sampleWidth / imgRatio;
            }
        } else {
            if (_img.height > maxHeight) {
                sampleHeight = maxHeight;
                sampleWidth = sampleHeight * imgRatio;
            }
        }
        return {
            width: sampleWidth,
            height: sampleHeight
        };
    }

    this.setImageMaxSize = function(width, height) {
        let size = _calcSizeByMax(width, height);
        return this.setImageSize(size.width, size.height);
    }

    this.setImageSize = function(width, height) {
        if (width <= 0 || height <= 0) {
            throw 'invalid size value for the image';
        }
        _targetSize = {
            width: width,
            height: height
        }
        return this;
    }

    //type如果为空，保持原来的，如果用最好的，显示调用getBestType并传入
    this.getImageDataURL = function(type = '', quality = 0.95) {
        console.error(_file)
        _lastImageType = type || _img;
        console.log('target type', _lastImageType);
        if (_targetSize) {
            targetWidth = _targetSize.width;
            targetHeight = _targetSize.height;
        } else {
            targetWidth = _img.width;
            targetHeight = _img.height;
        }
        _canvas.width = targetWidth;
        _canvas.height = targetHeight;
        _context.clearRect(0, 0, targetWidth, targetHeight);
        _context.drawImage(_img, 0, 0, targetWidth, targetHeight);

        return _canvas.toDataURL(`image/${_lastImageType}`, quality);
    }

    //在getImageDataURL()后获取图片的格式
    this.getLastImageType = function() {
        return _lastImageType;
    }
}
